package cn.com.zero.manager.auth.controller;

import cn.com.zero.api.log.annotation.Log;
import cn.com.zero.base.vo.ResponseVO;
import cn.com.zero.db.vo.PageVO;
import cn.com.zero.manager.auth.constant.LogType;
import cn.com.zero.manager.auth.constant.ValidationRule;
import cn.com.zero.manager.auth.enums.StatusEnum;
import cn.com.zero.manager.auth.enums.TypeEnum;
import cn.com.zero.manager.auth.po.ManagerPO;
import cn.com.zero.manager.auth.service.IManageService;
import cn.com.zero.web.util.ExcelUtil;
import cn.com.zero.web.util.PageRequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.util.List;

/**
 * @author guoxin
 * @version 1.0.0
 * @Description
 * @date 2023/4/7 9:10
 */
@Api(tags = "管理员管理接口")
@Validated
@RestController
@RequestMapping("/manager/admin")
public class ManageController {

    /**
     * 管理员管理service
     */
    private IManageService manageService;

    @ApiOperation(value = "查询管理员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userID", value = "登录名"),
            @ApiImplicitParam(paramType = "query", name = "userName", value = "名称"),
            @ApiImplicitParam(paramType = "query", name = "status", value = "状态（0正常1冻结（禁用）2注销）")
    })
    @GetMapping("/list")
    public PageVO<ManagerPO> queryAdminList(@RequestParam(value = "userID", required = false) String userID
            , @RequestParam(value = "userName", required = false) String userName
            , @RequestParam(value = "status", required = false) Integer status) {
        return PageRequestUtil.getPageInfo(()->manageService.queryAdminList(userID,userName,status));
    }

    @ApiOperation(value = "查询管理员详情", notes = "查询指定管理员信息")
    @ApiImplicitParam(paramType = "path", name = "userID", required = true, value = "管理员编号")
    @GetMapping("/info/{userID}")
    public ManagerPO queryAdmin(@PathVariable("userID") String userID) {
        return manageService.queryAdmin(userID);
    }

    @Log(content = "添加管理员", logType = LogType.LOG_MANAGE, ignoreFields = "password")
    @ApiOperation(value = "添加管理员")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", required = true
                    , value = "登录名，不允许为空，长度在 " + ValidationRule.ADMIN_USERNAME_MIN + "~" + ValidationRule.ADMIN_USERNAME_MAX + " 之间，由字母、数字组成，最少包含一个字母"),
            @ApiImplicitParam(paramType = "query", name = "userName", required = true
                    , value = "名称，不允许为空，长度在 " + ValidationRule.ADMIN_NAME_MIN + "~" + ValidationRule.ADMIN_NAME_MAX + " 之间"),
            @ApiImplicitParam(paramType = "query", name = "password", required = true,
                    value = "重置密码，不允许为空，客户端限制 6~18 位长度，字母+数字"),
            @ApiImplicitParam(paramType = "query",name = "type",required = true,value = "管理员类型 0 超级管理员  1 普通管理"),
            @ApiImplicitParam(paramType = "query", name = "mobile", required = true
                    , value = "手机号，不允许为空，长度为 " + ValidationRule.MOBILE_PHONE_LENGTH),
            @ApiImplicitParam(paramType = "query", name = "note"
                    , value = "备注信息，长度在 " + ValidationRule.REMARK_LENGTH + " 以内"),
            @ApiImplicitParam(paramType = "query", name = "roles", required = true
                    , value = "角色编号")
    })
    @PostMapping("/add")
    public void addAdmin(
            @RequestParam("userId") String userId
            , @RequestParam("userName") String userName
            , @RequestParam("password") String password
            , @RequestParam("mobile") String mobile
            , @RequestParam("type")
            @Range(min = 0, max = 1, message = "管理员类型标识为非法数字")Integer type
            , @RequestParam(value = "note", required = false) String note
            , @RequestParam(value = "roles") String[] roles) {
        manageService.addAdmin(userId,userName,password,mobile,type,note,roles);
    }

    @Log(content = "修改管理员信息", logType = LogType.LOG_MANAGE)
    @ApiOperation(value = "修改管理员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userId", required = true, value = "管理员编号"),
            @ApiImplicitParam(paramType = "query", name = "userName"
                    , value = "管理员名称，不允许为空，长度在 " + ValidationRule.ADMIN_NAME_MIN + "~" + ValidationRule.ADMIN_NAME_MAX + " 之间"),
            @ApiImplicitParam(paramType = "query", name = "mobile"
                    , value = "手机号，不允许为空，长度为 " + ValidationRule.MOBILE_PHONE_LENGTH),
            @ApiImplicitParam(paramType = "query", name = "status"
                    , value = "状态（0正常1冻结（禁用）2注销）"),
            @ApiImplicitParam(paramType = "query", name = "note"
                    , value = "备注信息，长度在 " + ValidationRule.REMARK_LENGTH + " 以内"),
            @ApiImplicitParam(paramType = "query", name = "roles"
                    , value = "角色编号")
    })
    @PutMapping("/update/{userId}")
    public void updateAdminInfo(@PathVariable("userId") String userId,
                                @RequestParam(value = "name", required = false) String userName,
                                @Pattern(regexp = ValidationRule.MOBILE_EX) @RequestParam(value = "mobile", required = false) String mobile,
                                @RequestParam(value = "status", required = false) Integer status,
                                @Size(max = ValidationRule.REMARK_LENGTH, message = "{range}")
                                @RequestParam(value = "remark", required = false) String note,
                                @RequestParam(value = "roles") String[] roles) {
        manageService.updateAdminInfo(userId,userName,mobile,status,note,roles);
    }

    @Log(content = "重置管理员密码", logType = LogType.LOG_MANAGE, ignoreFields = "password")
    @ApiOperation(value = "重置管理员密码", notes = "修改其他管理员密码，所以不需要验证旧密码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userId", required = true, value = "管理员编号"),
            @ApiImplicitParam(paramType = "query", name = "password", required = true,
                    value = "重置密码，不允许为空，客户端限制 6~18 位长度，字母+数字，需要在客户端对新密码进行 MD5 加密后传到服务端")
    })
    @PutMapping("/resetPassword/{userId}")
    public void resetPassword(@PathVariable("userId") String userId
            , @Pattern(regexp = ValidationRule.PASSWORD_EX) @RequestParam("password") String password) {
        manageService.resetPassword(userId,password);
    }

    @Log(content = "修改管理员状态", logType = LogType.LOG_MANAGE)
    @ApiOperation(value = "修改管理员状态")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userId", required = true, value = "管理员编号"),
            @ApiImplicitParam(paramType = "query", name = "status", required = true, value = "状态（0正常1冻结（禁用）2注销）")
    })
    @PutMapping("/updateStatus/{userId}")
    public void updateStatus(
            @NotNull(message = "true") @PathVariable("userId") String userId
            , @NotNull(message = "{required}") @RequestParam("enabled") Integer status) {
        manageService.updateStatus(userId,status);
    }

    @Log(content = "删除管理员", logType = LogType.LOG_MANAGE)
    @ApiOperation(value = "删除管理员")
    @ApiImplicitParam(paramType = "query", name = "admins", required = true, value = "管理员编号集合，多个管理员之间逗号分割")
    @DeleteMapping("/deleteBatch")
    public void deleteAdminBatch(@RequestParam("admins") String[] admins) {
        manageService.deleteAdminBatch(admins);
    }

    @ApiOperation(value = "查询管理员拥有的角色", notes = "返回管理员拥有角色编号数组")
    @ApiImplicitParam(paramType = "path", name = "userId", required = true, value = "管理员编号")
    @GetMapping("/roles/{userId}")
    public String[] queryAdminRoleList(@PathVariable("userId") String userId) {
        return manageService.queryAdminRoleList(userId);
    }

    @Log(content = "重置管理员角色", logType = LogType.LOG_MANAGE)
    @ApiOperation(value = "重置管理员角色")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "userId", required = true, value = "管理员编号"),
            @ApiImplicitParam(paramType = "query", name = "roles", required = true, value = "重新赋予的角色编号数组")
    })
    @PutMapping("/resetRole/{userId}")
    public void resetRole(
            @NotNull(message = "true") @PathVariable("userId") String userId
            , @RequestParam("roles") String[] roles) {
        manageService.resetRole(userId,roles);
    }

    @ApiOperation(value = "导出管理员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "username", value = "登录名"),
            @ApiImplicitParam(paramType = "query", name = "name", value = "名称"),
            @ApiImplicitParam(paramType = "query", name = "status", value = "状态（0正常1冻结（禁用）2注销）")
    })
    @PostMapping("/list/export")
    public void export(@RequestParam(value = "username", required = false) String username
            , @RequestParam(value = "name", required = false) String name
            , @RequestParam(value = "status", required = false) Integer status
            , HttpServletResponse response) throws IOException {
        List<ManagerPO> managerPOS = manageService.queryAdminList(username, name, status);
        for(ManagerPO managerPO : managerPOS){
            String statusName = StatusEnum.getValueByName(managerPO.getStatus());
            managerPO.setStatusName(statusName);
            String TypeName = TypeEnum.getValueByName(managerPO.getType());
            managerPO.setTypeName(TypeName);
        }
        ExcelUtil.exportExcel(managerPOS,"管理员信息","管理员信息",ManagerPO.class,"管理员信息",response);
    }

    @ApiOperation(value = "检查登录名是否存在", notes = "判断登录名是否存在，true 存在 false 不存在，如果登录名格式不正确，则返回错误码")
    @ApiImplicitParam(paramType = "path", name = "username", required = true, value = "登录名，不允许为空，长度在 " + ValidationRule.ADMIN_USERNAME_MIN + "~" + ValidationRule.ADMIN_USERNAME_MAX + " 之间，由字母、数字组成，最少包含一个字母")
    @GetMapping("/isExistUsername/{username}")
    public ResponseVO isExistUsername(@PathVariable("username") String username) {
        ResponseVO responseVO = new ResponseVO();
        responseVO.setData(manageService.isExistUsername(username));
        return responseVO;
    }

    @ApiOperation(value = "检查手机号是否存在", notes = "判断手机号是否存在，true 存在 false 不存在，如果手机号格式不正确，则返回错误码")
    @ApiImplicitParam(paramType = "path", name = "mobile", required = true, value = "手机号")
    @GetMapping("/isExistMobilePhone/{mobile}")
    public ResponseVO isExistMobilePhone(@Pattern(regexp = ValidationRule.MOBILE_EX) @PathVariable("mobile") String mobile) {
        ResponseVO responseVO = new ResponseVO();
        responseVO.setData(manageService.isExistMobilePhone(mobile));
        return responseVO;
    }

    @Autowired
    public void setManageService(IManageService manageService) {
        this.manageService = manageService;
    }
}
